/*
 * show_mainwindow.cpp
 *
 *  Created on: Apr 30, 2011
 *      Author: tqlong
 */

#include <QtGui>
#include "show_mainwindow.h"
#include "viewer/viewer.h"

MainWindow::MainWindow(Viewer* viewer, QWidget* parent) :
    QMainWindow(parent), m_viewer(viewer)
{
  m_drawArea = new DrawArea(this);
  m_edtXMIN = new QLineEdit("-40");
  m_edtXMAX = new QLineEdit("40");
  m_edtYMIN = new QLineEdit("-40");
  m_edtYMAX = new QLineEdit("40");

  m_actRefresh = new QAction("Refresh", this);

  m_tbTools = this->addToolBar("Tools");
  m_tbTools->addAction(m_actRefresh);

  QHBoxLayout *axisLayout = new QHBoxLayout;
  axisLayout->addWidget(new QLabel("xmin")); axisLayout->addWidget(m_edtXMIN);
  axisLayout->addWidget(new QLabel("xmax")); axisLayout->addWidget(m_edtXMAX);
  axisLayout->addWidget(new QLabel("ymin")); axisLayout->addWidget(m_edtYMIN);
  axisLayout->addWidget(new QLabel("ymax")); axisLayout->addWidget(m_edtYMAX);
  QVBoxLayout *layout = new QVBoxLayout;
  layout->addLayout(axisLayout);
  layout->addWidget(m_drawArea);

  QWidget *c = new QWidget;
  c->setLayout(layout);
  setCentralWidget(c);

  connect(m_edtXMIN, SIGNAL(returnPressed()), m_drawArea, SLOT(update()));
  connect(m_edtYMIN, SIGNAL(returnPressed()), m_drawArea, SLOT(update()));
  connect(m_edtXMAX, SIGNAL(returnPressed()), m_drawArea, SLOT(update()));
  connect(m_edtYMAX, SIGNAL(returnPressed()), m_drawArea, SLOT(update()));

  connect(m_actRefresh, SIGNAL(triggered()), this, SLOT(slot_refresh()));

  m_drawArea->setFixedSize(QSize(800, 800));
}

void MainWindow::plot(QWidget* area)
{
  Plotter pl(area);
  prepareAxis(pl);

  if (m_viewer)
    m_viewer->plot(pl);
}

void MainWindow::prepareAxis(Axis&  axis)
{
  bool okxmin = false, okxmax = false, okymin = false, okymax = false;
  double xmin, xmax, ymin, ymax;
  xmin = m_edtXMIN->text().toDouble(&okxmin);
  xmax = m_edtXMAX->text().toDouble(&okxmax);
  ymin = m_edtYMIN->text().toDouble(&okymin);
  ymax = m_edtYMAX->text().toDouble(&okymax);
  if (!(okxmin && okxmax && okymin && okymax)) {
    xmin = -10; ymin = -10;
    xmax = 10; ymax = 10;
  }
  axis.setBoundary(xmin, xmax, ymin, ymax);
}

// ============= SLOTS =================
void MainWindow::slot_refresh()
{
  m_viewer->reload();
  m_drawArea->update();
}
